// ============================================================================
// 数据模型验证函数
// ============================================================================

// Type imports are used in JSDoc comments and function signatures

/**
 * 验证结果接口
 */
export interface ValidationResult {
  isValid: boolean
  errors: string[]
}

/**
 * 创建验证结果
 */
function createValidationResult(isValid: boolean, errors: string[] = []): ValidationResult {
  return { isValid, errors }
}

// ============================================================================
// 基础验证函数
// ============================================================================

/**
 * 验证字符串是否非空
 */
export function isNonEmptyString(value: any, fieldName: string): string | null {
  if (typeof value !== 'string' || value.trim().length === 0) {
    return `${fieldName} must be a non-empty string`
  }
  return null
}

/**
 * 验证数字是否为正整数
 */
export function isPositiveInteger(value: any, fieldName: string): string | null {
  if (!Number.isInteger(value) || value <= 0) {
    return `${fieldName} must be a positive integer`
  }
  return null
}

/**
 * 验证日期是否有效
 */
export function isValidDate(value: any, fieldName: string): string | null {
  if (!(value instanceof Date) || isNaN(value.getTime())) {
    return `${fieldName} must be a valid Date`
  }
  return null
}

/**
 * 验证枚举值
 */
export function isValidEnum<T extends string>(
  value: any,
  validValues: readonly T[],
  fieldName: string
): string | null {
  if (!validValues.includes(value)) {
    return `${fieldName} must be one of: ${validValues.join(', ')}`
  }
  return null
}

/**
 * 验证数组是否非空
 */
export function isNonEmptyArray(value: any, fieldName: string): string | null {
  if (!Array.isArray(value) || value.length === 0) {
    return `${fieldName} must be a non-empty array`
  }
  return null
}

/**
 * 验证URL格式
 */
export function isValidUrl(value: any, fieldName: string): string | null {
  if (typeof value !== 'string') {
    return `${fieldName} must be a string`
  }
  
  if (value.trim().length === 0) {
    return `${fieldName} must be a valid URL`
  }
  
  try {
    new URL(value)
    return null
  } catch {
    return `${fieldName} must be a valid URL`
  }
}

/**
 * 验证邮箱格式
 */
export function isValidEmail(value: any, fieldName: string): string | null {
  if (typeof value !== 'string') {
    return `${fieldName} must be a string`
  }
  
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(value)) {
    return `${fieldName} must be a valid email address`
  }
  return null
}

// ============================================================================
// 用户相关验证
// ============================================================================

/**
 * 验证用户对象
 */
export function validateUser(user: any): ValidationResult {
  const errors: string[] = []
  
  if (!user || typeof user !== 'object') {
    return createValidationResult(false, ['User must be an object'])
  }
  
  // 验证必填字段
  const idError = isPositiveInteger(user.id, 'id')
  if (idError) errors.push(idError)
  
  const usernameError = isNonEmptyString(user.username, 'username')
  if (usernameError) errors.push(usernameError)
  
  const nicknameError = isNonEmptyString(user.nickname, 'nickname')
  if (nicknameError) errors.push(nicknameError)
  
  const avatarError = isNonEmptyString(user.avatar, 'avatar')
  if (avatarError) errors.push(avatarError)
  
  const statusError = isValidEnum(user.status, ['online', 'offline', 'away'] as const, 'status')
  if (statusError) errors.push(statusError)
  
  const lastActiveTimeError = isValidDate(user.lastActiveTime, 'lastActiveTime')
  if (lastActiveTimeError) errors.push(lastActiveTimeError)
  
  return createValidationResult(errors.length === 0, errors)
}

/**
 * 验证好友对象
 */
export function validateFriend(friend: any): ValidationResult {
  const errors: string[] = []
  
  // 首先验证基础用户信息
  const userValidation = validateUser(friend)
  if (!userValidation.isValid) {
    errors.push(...userValidation.errors)
  }
  
  if (!friend || typeof friend !== 'object') {
    return createValidationResult(false, ['Friend must be an object'])
  }
  
  // 验证好友特有字段
  if (typeof friend.isFriend !== 'boolean') {
    errors.push('isFriend must be a boolean')
  }
  
  const friendshipStatusError = isValidEnum(
    friend.friendshipStatus,
    ['pending', 'accepted', 'blocked'] as const,
    'friendshipStatus'
  )
  if (friendshipStatusError) errors.push(friendshipStatusError)
  
  // addedAt 是可选的
  if (friend.addedAt !== undefined) {
    const addedAtError = isValidDate(friend.addedAt, 'addedAt')
    if (addedAtError) errors.push(addedAtError)
  }
  
  return createValidationResult(errors.length === 0, errors)
}

// ============================================================================
// 消息相关验证
// ============================================================================

/**
 * 验证消息内容
 */
export function validateMessageContent(content: any): ValidationResult {
  const errors: string[] = []
  
  if (!content || typeof content !== 'object') {
    return createValidationResult(false, ['MessageContent must be an object'])
  }
  
  // 至少要有一种内容类型
  const hasText = content.text && typeof content.text === 'string'
  const hasImage = content.imageUrl && typeof content.imageUrl === 'string'
  const hasFile = content.fileUrl && typeof content.fileUrl === 'string'
  
  if (!hasText && !hasImage && !hasFile) {
    errors.push('MessageContent must have at least one of: text, imageUrl, or fileUrl')
  }
  
  // 验证URL格式
  if (content.imageUrl !== undefined) {
    const imageUrlError = isValidUrl(content.imageUrl, 'imageUrl')
    if (imageUrlError) errors.push(imageUrlError)
  }
  
  if (content.fileUrl !== undefined) {
    const fileUrlError = isValidUrl(content.fileUrl, 'fileUrl')
    if (fileUrlError) errors.push(fileUrlError)
  }
  
  if (content.thumbnailUrl !== undefined) {
    const thumbnailUrlError = isValidUrl(content.thumbnailUrl, 'thumbnailUrl')
    if (thumbnailUrlError) errors.push(thumbnailUrlError)
  }
  
  // 验证文件大小
  if (content.fileSize !== undefined) {
    if (!Number.isInteger(content.fileSize) || content.fileSize < 0) {
      errors.push('fileSize must be a non-negative integer')
    }
  }
  
  // 验证语音时长
  if (content.duration !== undefined) {
    if (typeof content.duration !== 'number' || content.duration < 0) {
      errors.push('duration must be a non-negative number')
    }
  }
  
  return createValidationResult(errors.length === 0, errors)
}

/**
 * 验证消息对象
 */
export function validateMessage(message: any): ValidationResult {
  const errors: string[] = []
  
  if (!message || typeof message !== 'object') {
    return createValidationResult(false, ['Message must be an object'])
  }
  
  // 验证必填字段
  const messageIdError = isNonEmptyString(message.messageId, 'messageId')
  if (messageIdError) errors.push(messageIdError)
  
  const fromUserIdError = isPositiveInteger(message.fromUserId, 'fromUserId')
  if (fromUserIdError) errors.push(fromUserIdError)
  
  const conversationIdError = isNonEmptyString(message.conversationId, 'conversationId')
  if (conversationIdError) errors.push(conversationIdError)
  
  const messageTypeError = isValidEnum(
    message.messageType,
    ['TEXT', 'IMAGE', 'FILE', 'VOICE', 'SYSTEM'] as const,
    'messageType'
  )
  if (messageTypeError) errors.push(messageTypeError)
  
  const statusError = isValidEnum(
    message.status,
    ['SENDING', 'SENT', 'DELIVERED', 'READ', 'FAILED'] as const,
    'status'
  )
  if (statusError) errors.push(statusError)
  
  const createdAtError = isValidDate(message.createdAt, 'createdAt')
  if (createdAtError) errors.push(createdAtError)
  
  if (!Number.isInteger(message.sequence) || message.sequence < 0) {
    errors.push('sequence must be a non-negative integer')
  }
  
  if (typeof message.isRead !== 'boolean') {
    errors.push('isRead must be a boolean')
  }
  
  const senderNicknameError = isNonEmptyString(message.senderNickname, 'senderNickname')
  if (senderNicknameError) errors.push(senderNicknameError)
  
  const senderAvatarUrlError = isNonEmptyString(message.senderAvatarUrl, 'senderAvatarUrl')
  if (senderAvatarUrlError) errors.push(senderAvatarUrlError)
  
  // 验证消息内容
  const contentValidation = validateMessageContent(message.content)
  if (!contentValidation.isValid) {
    errors.push(...contentValidation.errors)
  }
  
  // 验证可选字段
  if (message.toUserId !== undefined) {
    const toUserIdError = isPositiveInteger(message.toUserId, 'toUserId')
    if (toUserIdError) errors.push(toUserIdError)
  }
  
  if (message.groupId !== undefined) {
    const groupIdError = isPositiveInteger(message.groupId, 'groupId')
    if (groupIdError) errors.push(groupIdError)
  }
  
  if (message.replyToMessageId !== undefined) {
    const replyToMessageIdError = isNonEmptyString(message.replyToMessageId, 'replyToMessageId')
    if (replyToMessageIdError) errors.push(replyToMessageIdError)
  }
  
  return createValidationResult(errors.length === 0, errors)
}

// ============================================================================
// 会话相关验证
// ============================================================================

/**
 * 验证会话对象
 */
export function validateConversation(conversation: any): ValidationResult {
  const errors: string[] = []
  
  if (!conversation || typeof conversation !== 'object') {
    return createValidationResult(false, ['Conversation must be an object'])
  }
  
  // 验证必填字段
  const idError = isNonEmptyString(conversation.id, 'id')
  if (idError) errors.push(idError)
  
  const typeError = isValidEnum(
    conversation.type,
    ['PRIVATE', 'GROUP'] as const,
    'type'
  )
  if (typeError) errors.push(typeError)
  
  const participantsError = isNonEmptyArray(conversation.participants, 'participants')
  if (participantsError) errors.push(participantsError)
  
  // 验证参与者都是正整数
  if (Array.isArray(conversation.participants)) {
    conversation.participants.forEach((participantId: any, index: number) => {
      const participantError = isPositiveInteger(participantId, `participants[${index}]`)
      if (participantError) errors.push(participantError)
    })
  }
  
  if (!Number.isInteger(conversation.unreadCount) || conversation.unreadCount < 0) {
    errors.push('unreadCount must be a non-negative integer')
  }
  
  const titleError = isNonEmptyString(conversation.title, 'title')
  if (titleError) errors.push(titleError)
  
  const avatarError = isNonEmptyString(conversation.avatar, 'avatar')
  if (avatarError) errors.push(avatarError)
  
  const updatedAtError = isValidDate(conversation.updatedAt, 'updatedAt')
  if (updatedAtError) errors.push(updatedAtError)
  
  const createdAtError = isValidDate(conversation.createdAt, 'createdAt')
  if (createdAtError) errors.push(createdAtError)
  
  if (typeof conversation.isActive !== 'boolean') {
    errors.push('isActive must be a boolean')
  }
  
  if (typeof conversation.isMuted !== 'boolean') {
    errors.push('isMuted must be a boolean')
  }
  
  // 验证可选的最后一条消息
  if (conversation.lastMessage !== undefined) {
    const lastMessageValidation = validateMessage(conversation.lastMessage)
    if (!lastMessageValidation.isValid) {
      errors.push(...lastMessageValidation.errors.map(error => `lastMessage.${error}`))
    }
  }
  
  return createValidationResult(errors.length === 0, errors)
}

// ============================================================================
// API 请求验证
// ============================================================================

/**
 * 验证登录请求
 */
export function validateLoginRequest(request: any): ValidationResult {
  const errors: string[] = []
  
  if (!request || typeof request !== 'object') {
    return createValidationResult(false, ['LoginRequest must be an object'])
  }
  
  const usernameError = isNonEmptyString(request.username, 'username')
  if (usernameError) errors.push(usernameError)
  
  const passwordError = isNonEmptyString(request.password, 'password')
  if (passwordError) errors.push(passwordError)
  
  // 密码长度验证
  if (typeof request.password === 'string' && request.password.length < 6) {
    errors.push('password must be at least 6 characters long')
  }
  
  // rememberMe 是可选的布尔值
  if (request.rememberMe !== undefined && typeof request.rememberMe !== 'boolean') {
    errors.push('rememberMe must be a boolean')
  }
  
  return createValidationResult(errors.length === 0, errors)
}

/**
 * 验证发送消息请求
 */
export function validateSendMessageRequest(request: any): ValidationResult {
  const errors: string[] = []
  
  if (!request || typeof request !== 'object') {
    return createValidationResult(false, ['SendMessageRequest must be an object'])
  }
  
  const conversationIdError = isNonEmptyString(request.conversationId, 'conversationId')
  if (conversationIdError) errors.push(conversationIdError)
  
  const messageTypeError = isValidEnum(
    request.messageType,
    ['TEXT', 'IMAGE', 'FILE', 'VOICE', 'SYSTEM'] as const,
    'messageType'
  )
  if (messageTypeError) errors.push(messageTypeError)
  
  // 验证消息内容
  const contentValidation = validateMessageContent(request.content)
  if (!contentValidation.isValid) {
    errors.push(...contentValidation.errors.map(error => `content.${error}`))
  }
  
  // 验证可选字段
  if (request.replyToMessageId !== undefined) {
    const replyToMessageIdError = isNonEmptyString(request.replyToMessageId, 'replyToMessageId')
    if (replyToMessageIdError) errors.push(replyToMessageIdError)
  }
  
  if (request.clientMessageId !== undefined) {
    const clientMessageIdError = isNonEmptyString(request.clientMessageId, 'clientMessageId')
    if (clientMessageIdError) errors.push(clientMessageIdError)
  }
  
  return createValidationResult(errors.length === 0, errors)
}

// ============================================================================
// 导出所有验证函数
// ============================================================================

export const validators = {
  // 基础验证
  isNonEmptyString,
  isPositiveInteger,
  isValidDate,
  isValidEnum,
  isNonEmptyArray,
  isValidUrl,
  isValidEmail,
  
  // 数据模型验证
  validateUser,
  validateFriend,
  validateMessage,
  validateMessageContent,
  validateConversation,
  
  // API 请求验证
  validateLoginRequest,
  validateSendMessageRequest
}

export default validators